<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData(newValue, oldValue) {
      this.initChart()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      const legend = this.chartData.legend
      const title = this.chartData.title
      const data = this.chartData.data

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c}分 ({d}%)'
        },
        legend: {
          right: 30,
          bottom: 20,
          top: 40,
          type: 'scroll',
          orient: 'vertical',
          data: legend
        },
        title: {
          text: title,
          left: 'center',
          top: '',
          textStyle: {
            color: 'black',
            fontSize: 20,
            fontWeight: 400
          }
        },
        series: [
          {
            name: title,
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '60%'],
            data: data,
            animationEasing: 'cubicInOut',
            animationDuration: 2600,
            label: {
              formatter: '{b}: {c}分'
            }
          }
        ]
      })
    }
  }
}
</script>
